<template>
  <!-- 主容器 -->
  <div class="container" v-if="currentMode !== 'null'">
    <!-- 标题 -->
    <h2>{{ formTitle }}</h2>
    
    <!-- 模式切换按钮 -->
    <div class="form-toggle">
      <button @click="switchMode('login')" :class="{ active: currentMode === 'login' }">登录</button>
      <button @click="switchMode('register')" :class="{ active: currentMode === 'register' }">注册</button>
    </div>

    <!-- 登录模式下的用户类型选择 -->
    <div class="form-type" v-if="currentMode === 'login'">
      <select v-model="loginType">
        <option value="user">用户登录</option>
        <option value="manager">管理员登录</option>
      </select>
    </div>

    <!-- 表单 -->
    <form @submit.prevent="submitForm">
      <!-- 注册模式下的用户名输入 -->
      <div class="form-group" v-if="currentMode === 'register'">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="form.username" @input="validateUsername" required>
        <span v-if="!usernameValid" class="error-message">用户名不得超过20个字符</span>
      </div>
      
      <!-- 注册模式下的密码输入 -->
      <div class="form-group" v-if="currentMode === 'register'">
        <label for="password">密码</label>
        <input type="password" id="password" v-model="form.password" @input="validatePassword" required>
        <span v-if="!passwordValid" class="error-message">密码必须大于4个字符，包含数字和字母</span>
      </div>
      
      <!-- 注册模式下的确认密码输入 -->
      <div class="form-group" v-if="currentMode === 'register'">
        <label for="confirmPassword">确认密码</label>
        <input 
          type="password" 
          id="confirmPassword" 
          v-model="form.confirmPassword" 
          @input="validateConfirmPassword" 
          required
        >
        <span v-if="!confirmPasswordValid" class="error-message">两次输入的密码不一致</span>
      </div>
      
      <!-- 注册模式下的个性签名输入 -->
      <div class="form-group" v-if="currentMode === 'register'">
        <label for="personalSignature">个性签名</label>
        <input type="text" id="personalSignature" v-model="form.personalSignature" required>
      </div>
      
      <!-- 注册模式下的生日输入 -->
      <div class="form-group" v-if="currentMode === 'register'">
        <label for="birthday">生日</label>
        <input 
          type="date" 
          id="birthday" 
          v-model="form.birthday" 
          @change="validateBirthday" 
          required
        >
        <span v-if="!birthdayValid" class="error-message">生日不能是未来的日期</span>
      </div>
      
      <!-- 登录模式下的用户名输入 -->
      <div class="form-group" v-if="currentMode === 'login'">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="form.username" required>
      </div>
      
      <!-- 登录模式下的密码输入 -->
      <div class="form-group" v-if="currentMode === 'login'">
        <label for="password">密码</label>
        <input type="password" id="password" v-model="form.password" required>
      </div>
      
      <!-- 提交按钮 -->
      <button type="submit" :disabled="isSubmitting">{{ submitText }}</button>
    </form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useRouter } from 'vue-router';

// 基础URL
const BASE_URL = 'http://localhost:8080/lzl_content2_war_exploded';

export default defineComponent({
  data() {
    return {
      currentMode: 'login' as 'login' | 'register' | 'null', // 当前模式，默认为登录
      loginType: 'user' as 'user' | 'manager', // 登录类型，默认为用户登录
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        personalSignature: '',
        birthday: '',
      }, // 表单数据
      usernameValid: true, // 用户名校验结果
      passwordValid: true, // 密码校验结果
      confirmPasswordValid: true, // 确认密码校验结果
      birthdayValid: true, // 生日校验结果
      isSubmitting: false, // 提交状态
    };
  },
  setup() {
    const router = useRouter();
    return { router };
  },
  computed: {
    // 表单标题
    formTitle(): string {
      return this.currentMode === 'register' 
        ? '用户注册' 
        : this.loginType === 'user' 
          ? '用户登录' 
          : '管理员登录';
    },
    // 提交按钮文本
    submitText(): string {
      return this.currentMode === 'login' ? '登录' : '注册';
    }
  },
  watch: {
    // 监听登录类型变化，重置表单
    loginType(newVal, oldVal) {
      if (newVal !== oldVal && this.currentMode === 'login') {
        this.form.username = '';
        this.form.password = '';
      }
    }
  },
  methods: {
    // 切换模式
    switchMode(mode: 'login' | 'register') {
      this.currentMode = mode;
      this.form = {
        username: '',
        password: '',
        confirmPassword: '',
        personalSignature: '',
        birthday: '',
      };
      this.usernameValid = true;
      this.passwordValid = true;
      this.confirmPasswordValid = true;
      this.birthdayValid = true;
    },
    // 提交表单
    async submitForm() {
      if (this.isSubmitting) return;
      this.isSubmitting = true;

      if (this.currentMode === 'register') {
        // 注册模式下进行输入校验
        if (!this.usernameValid || !this.passwordValid || !this.confirmPasswordValid || !this.birthdayValid) {
          alert('请检查输入的有效性！');
          this.isSubmitting = false;
          return;
        }
        if (this.form.password !== this.form.confirmPassword) {
          alert('两次输入的密码不一致！');
          this.isSubmitting = false;
          return;
        }
      }

      try {
        // 构造请求URL
        const url = `${BASE_URL}/${this.currentMode === 'register' 
          ? 'userRegister' 
          : this.loginType === 'user' 
            ? 'userLogin' 
            : 'managerLogin'}`;

        const response = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            username: this.form.username,
            password: this.form.password,
            ...(this.currentMode === 'register' && {
              personalSignature: this.form.personalSignature,
              birthday: this.form.birthday
            })
          }),
        });

        const data = await response.json();

        if (response.ok) {
          if (this.currentMode === 'register') {
            alert('注册成功！');
            this.switchMode('login');
          } else {
            localStorage.setItem('token', data.token);
            localStorage.setItem('username', data.username);
            localStorage.setItem('loginType', this.loginType);
            alert(`${this.loginType === 'user' ? '用户' : '管理员'}登录成功！`);
            const route = this.loginType === 'user' ? '/user-dashboard' : '/manager-dashboard';
            this.router.push(route);
            this.currentMode = 'null';
          }
        } else {
          alert(data.message || '操作失败！');
        }
      } catch (error) {
        console.error('Error:', error);
        alert('服务器错误！');
      } finally {
        this.isSubmitting = false;
      }
    },
    // 用户名校验
    validateUsername() {
      this.usernameValid = this.form.username.length <= 20;
    },
    // 密码校验
    validatePassword() {
      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{4,}$/;
      this.passwordValid = passwordRegex.test(this.form.password);
    },
    // 确认密码校验
    validateConfirmPassword() {
      this.confirmPasswordValid = this.form.password === this.form.confirmPassword;
    },
    // 生日校验
    validateBirthday() {
      const selectedDate = new Date(this.form.birthday);
      this.birthdayValid = selectedDate <= new Date();
    }
  }
});
</script>

  <style scoped>
  body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
  }
  
  .container {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  
  h2 {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .form-toggle {
    display: flex;
    margin-bottom: 20px;
  }
  
  .form-toggle button {
    flex: 1;
    padding: 8px;
    background-color: #f1f1f1;
    border: none;
    cursor: pointer;
  }
  
  .form-toggle button.active {
    background-color: #4CAF50;
    color: white;
  }
  
  .form-type {
    margin-bottom: 15px;
  }
  
  select {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .form-group {
    margin-bottom: 15px;
  }
  
  label {
    display: block;
    margin-bottom: 5px;
  }
  
  input {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  button[type="submit"] {
    width: 100%;
    padding: 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 10px;
  }
  
  button[type="submit"]:hover {
    background-color: #45a049;
  }
  
  .error-message {
    color: red;
    font-size: 12px;
    margin-top: 5px;
  }
  </style>